/*
 * Copyright (c) 2023 Maker Studio. All rights reserved.
 * Licensed under the Apache 2.0 license. See LICENSE file in the project root for details.
 */

#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_errno.h"

#define BAUD_RATE 9600
#define HIGH_TIME 1300
#define LOW_TIME 420
#define TX_PIN 8

/**
 * @brief Initialize the GPIO for the simulated UART TX pin.
 * 
 * This function initializes the GPIO pin used for transmitting data in the simulated UART.
 * It sets the pin as an output and configures it with a pull-up resistor.
 * 
 * @author Maker Studio
 * @license Apache 2.0
 */
void JQ8900_16p_init(void) {
    IoTGpioInit(TX_PIN);
    IoSetFunc(TX_PIN, IOT_IO_FUNC_GPIO_8_GPIO);
    IoTGpioSetDir(TX_PIN, IOT_GPIO_DIR_OUT);
    IoSetPull(TX_PIN, IOT_IO_PULL_UP);
    IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE1);
}

/**
 * @brief Send a single byte of data using the simulated UART.
 * 
 * This function sends a single byte of data by toggling the GPIO pin according to the
 * specified timing for high and low states. The data is transmitted bit by bit, starting
 * with the least significant bit (LSB).
 * 
 * @param addr The byte of data to be sent.
 * 
 * @author Maker Studio
 * @license Apache 2.0
 */
void SendData(uint8_t addr) {
    uint8_t i;
    IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE1);
    uapi_systick_delay_us(1000);

    IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE0);
    uapi_systick_delay_us(3000);

    for (i = 0; i < 8; i++) {
        IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE1);

        if (addr & 0x01) {
            uapi_systick_delay_us(HIGH_TIME);
            IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE0);
            uapi_systick_delay_us(LOW_TIME);
        } else {
            uapi_systick_delay_us(LOW_TIME);
            IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE0);
            uapi_systick_delay_us(HIGH_TIME);
        }
        addr >>= 1;
    }

    IoTGpioSetOutputVal(TX_PIN, IOT_GPIO_VALUE1);
}